package com.online.shopping.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.online.shopping.entity.RespBean;
import com.online.shopping.entity.ResultPage;
import com.online.shopping.pojo.TbContent;
import com.online.shopping.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/content_Ms")
public class ContentController {

	@Autowired
	private ContentService contentService;

	@GetMapping("/findAll")
	public ResultPage findAll(int pageNum, int pageSize){
		System.out.println("页码："+pageNum);
		System.out.println("每页记录数："+pageSize);

		PageHelper.startPage(pageNum, pageSize);
		Page<TbContent> page = (Page<TbContent>) contentService.findAllTbContent();

		ResultPage resultPage = new ResultPage();
		resultPage.setRows(page.getResult());
		resultPage.setTotal(page.getTotal());

		return resultPage;
	}

	@GetMapping("/findOneById/{id}")
	public TbContent findOneById(@PathVariable Long id){
		return contentService.findTbContentById(id);
	}

	@PostMapping("/add")
	public RespBean add(@RequestBody TbContent content){
		ContentController.printObj(content);
		System.out.println("category_id:"+content.getCategoryId());

		try{
			contentService.add(content);
			return RespBean.ok("添加成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("添加失败！");
		}
	}

	@PostMapping("/update")
	public RespBean update(@RequestBody TbContent content){
		ContentController.printObj(content);

		try{
			contentService.update(content);
			return RespBean.ok("修改成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("修改失败！");
		}
	}

	private static void printObj(TbContent content){
		System.out.println("content id: "+content.getId());
		System.out.println("content title: "+content.getTitle());
	}

	@PostMapping("/delete")
	public RespBean delete(@RequestBody Long[] ids){
		System.out.println("id[]: "+ids);

		try{
			contentService.delete(ids);
			return RespBean.ok("删除成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("删除失败！");
		}
	}

	@GetMapping("/findAllContentCategory")
	public List findAllContentCategory(){
		return contentService.findAllContentCategory();
	}

	@GetMapping("/findByCategoryId/{categoryId}")
	public List findByCategoryId(@PathVariable Long categoryId){
		System.out.println("categoryId："+categoryId);
		return contentService.findByCategoryId(categoryId);
	}
}
